﻿using Epilog.Core.Model;
using Epilog.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Epilog.Controllers
{
    [Authorize(Roles="BlogAuthor")]
    public class PostController : Controller
    {
        EpilogContext context = new EpilogContext();


        //
        // GET: /Post/
        [AllowAnonymous]
        public ActionResult Index()
        {
            IEnumerable<BlogPost> posts;
            if (User.IsInRole("BlogAuthor"))
            {
                posts = context.Blogs.SelectMany(x => x.Posts).OrderBy(x => x.BlogPostCreated);
            }
            else
            {
                posts = context.Blogs.SelectMany(x => x.Posts)
                    .Where(p => p.BlogPostStatus == BlogPostStatusType.Public)
                    .OrderBy(p => p.BlogPostPublished);
            }
            return View(posts);
        }

        public ActionResult View(int id)
        {
            BlogPost post = context.Blogs.First().Posts.SingleOrDefault(p => p.BlogPostId == id && p.BlogPostStatus == BlogPostStatusType.Public);

            if (post == null) return HttpNotFound();

            ViewBag.Preview = false;

            return View("View", post);
        }

        public ActionResult Preview(int id)
        {
            BlogPost post = context.Blogs.First().Posts.SingleOrDefault(p => p.BlogPostId == id);

            if (post == null) return HttpNotFound();

            ViewBag.Preview = true;

            return View("View", post);
        }

        public ActionResult Edit(int id = 0)
        {
             
            return View();
        }

        public ActionResult SaveDraft(BlogPost post)
        {
            //TODO: Save
            BlogPost existing = context.Blogs.First().Posts.SingleOrDefault(p => p.BlogPostId == post.BlogPostId);
            if (existing == null)
            {
                post.BlogPostCreated = DateTime.Now;
                context.Blogs.First().Posts.Add(post);
            }
            else
            {
                context.Entry(existing).CurrentValues.SetValues(post);
                existing.BlogPostEdited = DateTime.Now;
            }
            return RedirectToAction("Edit", new { id = post.BlogPostId });
        }

        public ActionResult Publish(int id)
        {

            return RedirectToAction("Edit", new { id = id });
        }

    }
}
